package cn.fl.ref.fnovercollinfo.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.service.IFncPrjBscInfoService;
import cn.fl.ref.fncprjbscinfo.vo.FncPrjBscInfoVO;
import cn.fl.ref.fnovercollinfo.service.IFncOverCollInfoService;
import cn.fl.ref.fnovercollinfo.vo.FncOverCollInfoVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.ref.mrgnmanageinfo.vo.MrgnDetailInfoVO;
import cn.fl.ref.mrgnmanageinfo.vo.MrgnManageInfoVO;
import cn.fl.ref.mrgnmanageinfo.vo.MrgnTkOffInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.utils.JsonUtil;
import cn.fl.warrant.vo.ArcBorrowDetailVO;
import cn.fl.warrant.vo.ArcBorrowMainVO;
import cn.fl.warrant.vo.ArcMgrMainVO;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.ref.fncprjbscinfo.condition.FncPrjBscInfoQueryCondition;
import fl.ref.fnovercollinfo.condition.FncOverCollInfoQueryCondition;
import fl.ref.fnovercollinfo.dto.FncOverCollInfoDTO;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.mrgnmanageinfo.constant.MrgnManageInfoConstant;
import fl.warrant.facade.archive.condition.ArcBorrowDetailQueryCondition;
import fl.warrant.facade.archive.condition.ArcBorrowMainQueryCondition;
import fl.warrant.facade.archive.condition.ArcMgrMainQC;
import fl.warrant.facade.archive.constant.ArchiveConstants;

/**
 * @Description: 项目还款计划信息
 */
@Controller
@RequestMapping("/rfbuss/fnovercollinfo")
public class FncOverCollInfoController extends BaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(FncOverCollInfoController.class);

	@Autowired
	IFncOverCollInfoService fncOverCollInfoService;
	@Autowired
	IFriBaseInfoService friBaseInfoService;
	@Autowired
	private IFncPrjBscInfoService fncPrjBscInfoService;
	
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET })
	public ModelAndView toListPage(HttpServletRequest request,
			HttpServletResponse response) {

		logger.info("加载fnovercollinfo列表页面.");
		List<FriBaseInfoVO> friList = null;
		try {
			FriBaseInfoQueryCondition friqc = new FriBaseInfoQueryCondition();
			friList = friBaseInfoService.searchList(friqc);
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toListPage", "异常" + e.getMessage(), e);
		}
		// String fncInsId = request.getParameter("fncInsId");
		// String fncInsNm = request.getParameter("fncInsNm");
		// String fncInsShort = request.getParameter("fncInsShort");
		ModelAndView view = new ModelAndView(
				"/rfbuss/fnovercollinfo/fncOverCollInfoList");
		// view.addObject("fncInsId", fncInsId);
		// view.addObject("fncInsNm", fncInsNm);
		// view.addObject("fncInsShort", fncInsShort);
		view.addObject("frilist", JSON.toJSONString(friList));
		return view;
	}

	/**
	 * 初始化列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initList(HttpServletRequest request,
			HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");

		String id = request.getParameter("id");

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		String fncprjnm = request.getParameter("fncprjnm");
		String fncinsid = request.getParameter("fncinsid");

		FncOverCollInfoQueryCondition qc = new FncOverCollInfoQueryCondition();

		if (StringUtils.isNotEmpty(id)) {
			qc.setId(Long.parseLong(id));
		}

		if (StringUtils.isNotEmpty(fncprjnm)) {
			qc.setFncprjnm(fncprjnm);
		}
		if (StringUtils.isNotEmpty(fncinsid)) {
			qc.setFncinsid(fncinsid);
		}

		page.setCondition(qc);

		Pager pager = this.fncOverCollInfoService.searchListPage(page);
		List<FncOverCollInfoDTO> list = (List<FncOverCollInfoDTO>) pager
				.getResultList();
		setShowColor(list);// 设置超期状态提醒,颜色显示
		ListPageVO<FncOverCollInfoDTO> listPage = new ListPageVO<FncOverCollInfoDTO>(
				list, pager.getTotalCount());

		BaseLogUtils.info(logger, "initList",
				"查询数据完成. DATA:" + JSONObject.toJSONString(page),
				CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 计算两个日期相差几天
	 * @param smdate
	 * @param bdate
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}
	 
	/**
	 * 超期状态提醒,颜色显示 i. 绿色：当前时间——计划退回时间>7天； ii. 黄色：当前时间——计划退回时间<=7天； iii.
	 * 红色：当前时间>=计划退回时间（天）；
	 * 
	 * @param mrgnManageInfoVOList
	 */
	private void setShowColor(List<FncOverCollInfoDTO> fncOverCollInfoDTOList) {
		if (fncOverCollInfoDTOList != null) {

			for (FncOverCollInfoDTO fncOverCollInfoDTO : fncOverCollInfoDTOList) {
				if (fncOverCollInfoDTO.getReReturnTm() != null) {// 计划退回时间

					try {
						long betweenDays = daysBetween(new Date(),
								fncOverCollInfoDTO.getReReturnTm());
						BaseLogUtils.info(logger, "setShowColor",
								"betweenDays:" + betweenDays,
								CurrentThreadContext.getCurrentUserName());
						if (betweenDays > 7) {
							fncOverCollInfoDTO.setShowColor("green");
						} else if (betweenDays > 0 && betweenDays <= 7) {
							fncOverCollInfoDTO.setShowColor("yellow");
						} else {
							fncOverCollInfoDTO.setShowColor("red");
						}
					} catch (ParseException e) {
						e.printStackTrace();
						BaseLogUtils.info(logger, "", e.getMessage(),
								CurrentThreadContext.getCurrentUserName());
					}
				}
			}
		}
	}

	

	/**
	 * 到授信新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		FncOverCollInfoVO vo = this.fncOverCollInfoService.selectById(Long
				.parseLong(id));
		ModelAndView view = new ModelAndView(
				"/rfbuss/fnovercollinfo/fncOverCollInfoRefund");
		view.addObject("focvo", vo);
		return view;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String prjId = request.getParameter("prjId");

		String payId = request.getParameter("payId");

		String payPd = request.getParameter("payPd");

		String transTm = request.getParameter("transTm");

		String transSt = request.getParameter("transSt");

		String transAm = request.getParameter("transAm");

		String transBank = request.getParameter("transBank");

		String transAcc = request.getParameter("transAcc");
		
		String accNo = request.getParameter("accNo");

		String insAccId = request.getParameter("insAccId");
		
		
		FncOverCollInfoVO entity = new FncOverCollInfoVO();
		if (StringUtils.isNotEmpty(prjId)) {
			entity.setPrjId(Long.parseLong(prjId));
		}
		if (StringUtils.isNotEmpty(payId)) {
			entity.setPayId(Long.parseLong(payId));
		}
		if (StringUtils.isNotEmpty(payPd)) {
			entity.setPayPd(Long.parseLong(payPd));
		}
		if (StringUtils.isNotEmpty(transTm)) {
			entity.setTransTm(DateUtils.formatStringToDate(transTm,
					DateUtils.YYYY_MM_DD));
		}
		// if (StringUtils.isNotEmpty(transSt)) {
		entity.setTransSt(0);// 未到账:0 已到账：1
		// }
		if (StringUtils.isNotEmpty(transAm)) {
			entity.setTransAm(DecimalUtils.convertYuanToFen(Double
					.parseDouble(transAm)));
		}
		if (StringUtils.isNotEmpty(transBank)) {
			entity.setTransBank(transBank);

		}
		if (StringUtils.isNotEmpty(transAcc)) {
			entity.setTransAcc(transAcc);

		}
		
		String transAccNoReturn = request.getParameter("transAccNoReturn");
		if (StringUtils.isNotEmpty(transAccNoReturn)) {
			entity.setTransAccNoReturn(DecimalUtils.convertYuanToFen(Double
					.parseDouble(transAccNoReturn)));
		}
		
		entity.setAccNo(accNo);
		
		if (StringUtils.isNotEmpty(insAccId)) {
			entity.setPayAccountId(Long.valueOf(insAccId));
		}
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,
				"新增成功!");

		try {
			
			//1、验证
			if(entity.getPrjId() == null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("新增失败!entity.getPrjId() = null");
				BaseLogUtils.error(logger, "add", "新增失败!entity.getPrjId() == null" ,CurrentThreadContext.getCurrentUserName());
				return result;
			}
			
			FncPrjBscInfoVO fncPrjBscInfoVO = this.fncPrjBscInfoService.selectById(entity.getPrjId());
			 if(fncPrjBscInfoVO ==  null) {
				 result.setSuccess(BaseConstant.IS_YESNO_NO);
				 result.setInfo("新增失败!没有查询到项目信息 entity.getPrjId()："+entity.getPrjId());
				 BaseLogUtils.error(logger, "add", "新增失败!没有查询到项目信息 entity.getPrjId()："+entity.getPrjId() ,CurrentThreadContext.getCurrentUserName());
				 return result;
			 }
			 
			 if(fncPrjBscInfoVO.getFoSt() != null && fncPrjBscInfoVO.getFoSt() == 1) {
				 result.setSuccess(BaseConstant.IS_YESNO_NO);
				 result.setInfo("已有超额质押退回流程审批中，请审批完成后，再发起新流程 entity.getPrjId():"+entity.getPrjId());
				 BaseLogUtils.error(logger, "", "已有超额质押退回流程审批中，请审批完成后，再发起新流程 entity.getPrjId():"+entity.getPrjId() ,CurrentThreadContext.getCurrentUserName());
				 return result;
			 }
			 
			 //2 新增业务数据
			Long mainId = this.fncOverCollInfoService.add(entity);
			
			if(mainId == null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("新增失败!mainId=null");
				BaseLogUtils.error(logger, "add", "新增失败!mainId=null" ,CurrentThreadContext.getCurrentUserName());
			}
			
			//3  发起业务流程:再融资超额质押退回流程
			result = startFlow(mainId);
			
			//4 更改项目的超额质押退回流程状态为 1：流程中
			if(result != null && result.getSuccess() == 1) {
				fncPrjBscInfoVO.setFoSt(1);
				fncPrjBscInfoService.modify(fncPrjBscInfoVO);
			}
			
			
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			BaseLogUtils.error(logger, "add", "新增数据失败" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/remove.do", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public DataResultVO remove(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,
				"删除成功!");
		try {
			this.fncOverCollInfoService.removeById(Long.parseLong(id));
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("删除成功!");
			BaseLogUtils.info(logger, "remove", "删除数据,主键[" + id + "].",
					CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "remove",
					"删除数据失败,主键[" + id + "]." + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "remove",
					"删除数据失败,主键[" + id + "]." + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 详情
	 */
	@RequestMapping(value = "/view.do")
	public Object view(FncOverCollInfoVO vo, HttpServletRequest request) {

		if(vo.getId() != null) {
			request.setAttribute("vo", this.fncOverCollInfoService.selectById(vo.getId()));
		}
		return "/rfbuss/fnovercollinfo/fncOverCollInfoView";
	}
	
	/**
	 * 超额抵押退回记录
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/returnRecordPage.do")
	@ResponseBody
	public Object returnRecordPage(FncOverCollInfoQueryCondition qc,HttpServletRequest request) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

	
		page.setCondition(qc);

		page = this.fncOverCollInfoService.returnRecordPage(page);
		List<Map<String, Object>> list = (List<Map<String, Object>>) page.getResultList();
		BaseLogUtils.info(logger, "returnList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return new ListPageVO<Map<String, Object>>(list, page.getTotalCount());
	}
	
	/**
	 * 发起超额抵押退回流程
	 */
	private DataResultVO startFlow(Long id) {
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "borrowApplyStartFlow", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			//流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setBusinessKey(String.valueOf(id));
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(MrgnManageInfoConstant.REF_FLOW_S_H_MRGNR);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);
			flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm());
			flowStartParamsDTO.setCstNm("");//任务中承租人信息
			flowStartParamsDTO.setModelTyp("R018");//需要和流程配置中的模块类型匹配
			
            
			DataResultDTO dataResultDTO = this.fncOverCollInfoService.addFlowStart(flowStartParamsDTO);
			if(null!=dataResultDTO &&!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if(null!=dataResultDTO && null!=dataResultDTO.getData()){
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
				if(StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())){
	                result.setInfo("下一个节点操作人:"+flowStartedDTO.getNextOperUsrNames());
	            }else{
	                result.setInfo("流程发起成功");
	            }
			}
			
		}catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "startFlow", "错误[Exception],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" +e.getMessage(), CurrentThreadContext.getCurrentUserName());
			e.printStackTrace();
		}
		return result;
	}
	
	
	
	/**
	 * 流程页面
	 */
	@RequestMapping(value = "/flowView.do")
	public Object flowView(FncOverCollInfoQueryCondition qc, HttpServletRequest request) {

		if(qc.getId() != null) {
			request.setAttribute("m", fncOverCollInfoService.flowView(qc));
		}
		request.setAttribute("from",request.getParameter("from"));
		return "/rfbuss/fnovercollinfo/fncOverCollInfoFlowPage";
	}
	
	
	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do")
	@ResponseBody
	public Object modify(FncOverCollInfoVO vo,HttpServletRequest request){
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		try {
				
				vo.setCrtTm(new Date());
				vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				
				fncOverCollInfoService.modify(vo);
			
				BaseLogUtils.info(logger, "modify", "操作数据. DATA:" + JSONObject.toJSONString(vo), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			ex.printStackTrace();
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "modify", "操作数据失败.DATA:" + JSONObject.toJSONString(vo) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}
